import { decode, encode } from "cbor-x"
import { cfg } from "./config";

export interface ErrResp {
    err_code: number,
    err_msg: string,
}

export interface Void {}

export const post = async<T, R> (url: string, req: T) => {
    const buf = encode(req);
    const resp = await fetch(`${cfg.BASE_URL}${url}`, {
        method: 'POST',
        body: buf
    });
    if (resp.status != 200) {
        throw `${resp.statusText}`;
    }
    const respHead = resp.headers.get('resp');
    if (respHead == null) {
        throw `invalid resp head`;
    }

    if (respHead != 'ok') {
        const err = decode(new Uint8Array( await resp.arrayBuffer() )) as ErrResp;
        throw `err_code:${err.err_code} err_msg:${err.err_msg}`;
    }

    const data = await resp.arrayBuffer();
    if (data.byteLength == 0) {
        return {} as Void;
    }
    return decode( new Uint8Array(data) ) as R;
}


